package edu.upc.dew.controller;

import edu.upc.dew.dto.JsonResponse;
import edu.upc.dew.entity.Account;
import edu.upc.dew.filter.KeyCodeCheckFilter;
import edu.upc.dew.service.AccountService;
import edu.upc.dew.service.exception.BusinessException;
import edu.upc.dew.util.KeycodeManager;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author gian.corzo
 */
@Controller("accountsController")
public class AccountsController {

    @Autowired
    private AccountService accountService;

    private static final Logger logger = LoggerFactory.getLogger(AccountsController.class);

    @RequestMapping(value = "/authenticate",method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody JsonResponse authenticate(
            @RequestParam("email") String email,
            @RequestParam("password") String password) {

        boolean success = true;
        String errorMessage = null;
        Map<String,Object> jsonResponse = null;

        try {
            jsonResponse = accountService.authenticate(email,password);
            KeyCodeCheckFilter.registerKeycode(((Account)jsonResponse.get("account")).getId().toString(),
                    (String)jsonResponse.get("keycode"));
        } catch (BusinessException be) {
            errorMessage = be.getMessage();
            success = false;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            errorMessage = e.getMessage();
            success = false;
        }
        return new JsonResponse(success,errorMessage,jsonResponse);
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(@RequestParam("keycode") String keycode) {
        String accountId = KeycodeManager.getKey(keycode);
        KeyCodeCheckFilter.unregisterKeycode(accountId);
        return "login";
    }
}
